<script setup>
import SchedulingFrame from '../components/SchedulingFrame.vue';
import { storeToRefs } from 'pinia';
import { useItem } from '../../store/index.js';
import { createDeploymentHandler as createItem, updateDeploymentHandler as updateItem } from '../../api/deployment';
import { ElMessage,ElMessageBox  } from 'element-plus'
import DialogYaml from '../components/DialogYaml.vue';
import { obj2Yaml } from '../../utils/utils';
import StringOrNumber from '../components/StringOrNumber.vue';
import { ref ,onBeforeMount} from 'vue';
import {useRouter} from 'vue-router'
const router = useRouter()
const props = defineProps({
  method: {
    type: String,
    default: 'Create'
  }
})
const useItemer = useItem()
const showDetail = ref(false)
let yamlContent = ref('')
const submitRollback = (msg)=>{ 
  ElMessageBox.confirm(
    msg,
    '执行结果',
    {
      confirmButtonText: '查看列表',
      cancelButtonText: '继续编辑',
      type: 'success',
    }
  )
    .then(() => {
      //跳转到对应的列表页
      router.replace({
        path: '/deployment/list',
        query: {
          clusterId: useItemer.clusterId,
          namespace: useItemer.namespace,
          
        }
      })
    })
    .catch(() => {
      router.replace({
        path: '/deployment/edit',
        query: {
          clusterId: useItemer.clusterId,
          namespace: useItemer.namespace,
          name: useItemer.item.metadata.name,
          method: "Update"
        }
      })
    })
}
const submit = (tag, autoCreateService)=> {
  console.log('tag:', tag)
  console.log('item:', useItemer.item)
  // useItemer.item['apiVersion'] = 'apps/v1'
  // useItemer.item['Kind'] = 'Deployment'
  const item = {
      "apiVersion": "apps/v1",
      "kind": "Deployment",
      "metadata": useItemer.item.metadata,
      "spec": useItemer.item.spec
    }
  if (tag == 'yaml') {
    // 首先要把json转成yaml
    const yamlData = obj2Yaml(item)
    yamlContent.value = yamlData
    showDetail.value = true
  } else {
    const postData = {
      clusterId: useItemer.clusterId,
      namespace: useItemer.namespace,
      item: item,
      autoCreateService
    }
    if (props.method != "Update") {
        // 创建用户，异步的
        createItem(postData).then((response)=>{
          // console.log("response:", response)
          // ElMessage({
          //         message: response.data.message,
          //         type: 'success',
          // })
          // loading.value = false
          // emits('rollback')
          submitRollback(response.data.message)

        })
  } else {
      // 创建用户，异步的
      updateItem(postData).then((response)=>{
          // console.log("response:", response)
          // ElMessage({
          //         message: response.data.message,
          //         type: 'success',
          // })
          submitRollback(response.data.message)
      })
    }
  }

}
// 变更更新方式
const strategyChanged = (val) => {
    console.log("更新方式:", val)
    // 当更新方式为Recreate的时候，删除rollingUpdate
    if (val == "Recreate") {
        delete useItemer.item.spec.strategy.rollingUpdate
    } else if (val == "RollingUpdate") {
        useItemer.item.spec.strategy.rollingUpdate  = {
            maxSurge: "25%",
            maxUnavailable: "25%"
        }
    }
}
// 返回更新方式的类型
const strategyType = [
      {
          value: "RollingUpdate",
          label: "滚动更新"
      },
      {
          value: "Recreate",
          label: "先删除后重建"
      },
  ]
onBeforeMount(()=>{
  //创建的时候需要添加吗？ 不需要
  if(props.method == "Create"){
    useItemer.item.spec.strategy = {
        type: "RollingUpdate",
        rollingUpdate: {
            maxSurge: "25%",
            maxUnavailable: "25%"
        }
    }
  }
})  
const {clusterId, namespace,item} = storeToRefs(useItem())
</script>

<template>
  <SchedulingFrame :method="props.method" @submit="submit">
    <template #strategy>
         <!-- 插入更新方式 -->
        <el-col :span="6">
            <el-form-item label="更新方式" prop="spec.strategy">
                <el-select v-model="item.spec.strategy.type" style="width: 180px;" placeholder="选择更新方式" @change="strategyChanged">
                    <el-option
                    v-for="s in strategyType"
                    :key="s.value"
                    :label="s.label"
                    :value="s.value"
                    />
                </el-select>
            </el-form-item>
        </el-col>
        <el-col :span="6">
            <el-form-item label="最大不可用" prop="" v-if="item.spec.strategy.type=='RollingUpdate'">
                <!-- v-model:data v-model:visible modelValue update:modelValue-->
                <StringOrNumber v-model:data="item.spec.strategy.rollingUpdate.maxUnavailable" placeholder="最大不可用"></StringOrNumber>
                <!-- <el-input v-model.trim="item.spec.strategy.rollingUpdate.maxUnavailable" style="width: 64px;" /> -->
            </el-form-item>
        </el-col>
        <el-col :span="6">
            <el-form-item label="可超出最大值" prop=""  v-if="item.spec.strategy.type=='RollingUpdate'">
                <StringOrNumber v-model:data="item.spec.strategy.rollingUpdate.maxSurge" placeholder="可超出最大值"></StringOrNumber>
                <!-- <el-input v-model.trim="item.spec.strategy.rollingUpdate.maxSurge" style="width: 64px;" /> -->
            </el-form-item>
        </el-col>
    </template>
  </SchedulingFrame>
  <DialogYaml
  :cluster-id="clusterId"
  :namespace="namespace"
  :yaml-content="yamlContent"
  :show-dialog="showDetail"
  :method="props.method"
  @close-dialog-handler="(val)=>{showDetail = val}"
  >

  </DialogYaml>
</template>

<style scoped>

</style>
